package com.example.springboot.service;

import com.example.springboot.dto.PaymentDTO;
import com.example.springboot.entity.Payment;
import com.example.springboot.mapper.PaymentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class PaymentService {

    @Autowired
    private PaymentMapper paymentMapper;

    public Payment createPayment(PaymentDTO paymentDTO) {
        Payment payment = new Payment();
        payment.setOrderId(paymentDTO.getOrderId());
        payment.setUserId(paymentDTO.getUserId());
        payment.setOrderType(paymentDTO.getOrderType());  // 使用传递过来的 orderType

        payment.setOrderAmount(paymentDTO.getOrderAmount());
        payment.setPaymentMethod(paymentDTO.getPaymentMethod() != null ? paymentDTO.getPaymentMethod() : "default");
        payment.setPaymentStatus("pending");
        payment.setTransactionId(paymentDTO.getTransactionId());
        payment.setCreatedAt(LocalDateTime.now());
        payment.setUpdatedAt(LocalDateTime.now());
        paymentMapper.insert(payment);
        return payment;
    }

    public void updatePaymentStatus(String transactionId, String status) {
        Payment payment = paymentMapper.findByTransactionId(transactionId);
        if (payment == null) {
            throw new RuntimeException("支付记录未找到");
        }
        payment.setPaymentStatus(status);
        payment.setUpdatedAt(LocalDateTime.now());
        paymentMapper.update(payment);
    }

    // 根据订单ID和用户ID查找支付记录
    public Payment findPaymentByOrderIdAndUserIdAndType(Integer orderId, Integer userId, String orderType) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("orderId", orderId);
        params.put("orderType", orderType);
        return paymentMapper.findByUserIdAndOrderIdAndType(params);
    }



}
